package com.tensquare.user.interceptor;

import com.tensquare.user.util.UserConstant;
import com.tensquare.util.JwtUtil;
import com.tensquare.util.NotNullHelps;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserJwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil ;

    // 原则 ： 都放行 && 作用 ： 将请求头中包含token的令牌进行解析
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("## 经过了 UserJwtInterceptor @@");
        String header = request.getHeader(UserConstant.request_header);
        if (NotNullHelps.isNotNull(header) == true) {
            if (header.startsWith(UserConstant.request_header_start) == true) {
                String jwtToken = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(jwtToken);
                    String roles = (String) claims.get("roles");
                    if (NotNullHelps.isNotNull(roles) == true) {
                        if ("user".equals(roles) == true) {
                            request.setAttribute("claims_user", jwtToken);
                        } else if ("admin".equals(roles)) {
                            request.setAttribute("claims_admin", jwtToken);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("令牌--异常");
                }
            }
        }
        return true;
    }
}
